<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <!-- 1、创建 canvas 元素 -->
<canvas id="c"  style="border: 1px solid #ccc;width: 200px;" ></canvas>

<script>
  const cnv = document.getElementById('c')
  const cvs = cnv.getContext('2d',{
    willReadFrequently:true
  })
  const image = new Image()
  image.src = './img/R.jpg'
  image.onload = () => {
    cnv.width=image.width;
    cnv.height=image.height;

    cvs.drawImage(image, 0, 0)
  }
  cnv.addEventListener('click',e=>{
        const x =e.offsetX,y=e.offsetY;
        // 取出点击位置的像素点颜色
        const imgData = cvs.getImageData(0,0,cvs.width,cvs.height);
        console.log(imgData)
        const clickColor = getColor(x,y,imgData);
        const greenColor = [0,255,0,255];
        function _changeColor(x,y){
            if(x<0||x>=cvs.width||y<0||y>=cvs.height){
                return;
            }
            const color = getColor(x,y);
            if(diff(color,clickColor)>100){
                return;
            }
            if(diff(color,greenColor)===0){
                return;
            }
            const i = point2Index(x,y);
            imgData.data.set(greenColor,i)
            _changeColor(x+1,y);
            _changeColor(x-1,y);
            _changeColor(x,y+1);
            _changeColor(x,y-1);
        }
        // 修改内存中图片的颜色
        _changeColor(x,y);
        // 重新画图片
        ctx.putImageData(imgData,0,0)
  })

function point2Index(x,y){
    return (y*cvs.width+x)*4;
}

function getColor(x,y,imgData){
    const i = point2Index(x,y);
    return [imgData.data[i],imgData.data[i+1],imgData.data[i+2],imgData.data[i+3]]
}
  
function diff(color1,color2){
return (Math.abs(color1[0]-color2[0])+
    Math.abs(color1[1]-color2[1])+
    Math.abs(color1[2]-color2[2])+
    Math.abs(color1[3]-color2[3]));
}
</script>


</body>
</html>
